﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace Raytracererer
{
    class TexturedSphere : Sphere
    {
        Bitmap texture;
        Color[,] lightmap;
        int lightmapWidth;
        int lightmapHeight;

        public TexturedSphere(double radius, Vector3 position, Color color, Bitmap texture)
            : base(radius, position, color)
        {
            this.texture = texture;
            lightmapWidth = texture.Width;
            lightmapHeight = texture.Height;
            lightmap=new Color[lightmapWidth,lightmapHeight];
        }
        public override Color ColorAt(Vector3 position)
        {
            Vector3 relPos = (position - center).Normalized();
            double theta = Math.Acos(relPos.Y);
            double sigma = Math.PI + Math.Atan2(relPos.Z, -relPos.X);
            System.Drawing.Color c = texture.GetPixel((int)(sigma / 2 / Math.PI * (texture.Width - 1)),
                (int)(theta / Math.PI * (texture.Height - 1)));
            return new Color(c.R / 255.0, c.G / 255.0, c.B / 255.0) * color * lightmap[(int)(sigma / 2 / Math.PI * (lightmapWidth - 1)),
                (int)(theta / Math.PI * (lightmapHeight - 1))];
        }
        public void setLight(Vector3 position,Color col)
        {
            Vector3 relPos = (position - center).Normalized();
            double theta = Math.Acos(relPos.Y);
            double sigma = Math.PI + Math.Atan2(relPos.Z, -relPos.X);
            lightmap[(int)(sigma / 2 / Math.PI * (lightmapWidth - 1)),
                (int)(theta / Math.PI * (lightmapHeight - 1))] += col;
        }
    }
}
